<?php
namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Message;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use App\Models\Order;
use App\Models\OrderLog;
use App\Models\Payment;
use Log;
use App\Services\Payment\Sumpay\Sumpay;
use App\Services\Payment\Lianlianpay\Lianlianpay;
use Illuminate\Support\Facades\URL;

class OrderController extends Controller
{

    /**
     * @api {post} /order/list
     * 订单列表
     */
    public function list(Request $request)
    {
        $rules = [
            'page'            => 'integer|min:1',
            'per_page'        => 'required_with:page|integer|min:1',
            // 'status'          => 'integer|min:0'
        ];

        if ($error = $this->validateInput($rules)) {
            return $error;
        }

        $data = Order::getList($this->validated);

        return $this->output(200, $data);
    }

    /**
     * @api {post} /order/count
     * 订单数量统计
     */
    public function count(Request $request)
    {
        // 全部
        $all_count = Order::count();

        // 待支付
        $notpay_count = Order::where('status', 'active')->where('pay_status', 'notpay')->where('ship_status', 'notdelivery')->count();

        // 待发货
        $notdelivery_count = Order::where('status', 'active')->where('pay_status', 'paid')->where('ship_status', 'notdelivery')->count();

        // 已发货
        $shipped_count =  Order::where('status', 'done')->where('pay_status', 'paid')->where('ship_status', 'shipped')->count();

        // 已作废
        $invalid_count = Order::where('status', 'invalid')->count();

        $result = [
            'all_count' =>  $all_count,
            'notpay_count' => $notpay_count,
            'notdelivery_count' => $notdelivery_count,
            'shipped_count' => $shipped_count,
            'invalid_count' => $invalid_count,
        ];

        return $this->output(200, $result);
    }

    /**
     * @api {post} /order/info
     * 商品列表
     */
    public function info(Request $request)
    {
        $rules = [
            'order_id'          => 'required|integer|min:0'
        ];

        if ($error = $this->validateInput($rules)) {
            return $error;
        }

        $data = Order::getInfo($this->validated);

        return $this->output(200, $data);
    }

    /**
     * @api {post} /order/delivery
     * 订单发货
     */
    public function delivery(Request $request)
    {
        $rules = [
            'exchange_code'          => 'required|string'
        ];

        if ($error = $this->validateInput($rules)) {
            return $error;
        }

        $data = Order::toDelivery($this->validated);

        return $this->output(200, $data);
    }

    /**
     * @api {post} /order/create
     * 订单创建
     */
    public function create(Request $request)
    {
        $rules = [
            'goods'             => 'required|string',
            'type'              => 'required|string',
            // 'remark'            => 'string',
            'address_id'        => 'required|integer|min:0',
            'payment_code'      => 'required|string',
        ];

        if ($error = $this->validateInput($rules)) {
            return $error;
        }

        $member =  \Auth::guard('member')->user();
        // $goods = "[{"goods_id":1,"sku_id":1,"num":1},{"goods_id":1,"sku_id":2,"num":1}]";
        $this->validated['member'] = $member;

        $this->validated['goods'] = json_decode($this->validated['goods'], 1);

        $msg = '';
        $result = Order::create($this->validated, $msg);

        if (!$result)
        {
            return $this->output(200500, '', $msg);
        }

        return $this->output(200, $result);
    }

     /**
     * @api {post} /order/getPrice
     * 获取结算价格
     */
    public function getPrice(Request $request)
    {
        $rules = [
            'goods' => 'required|string',
        ];

        if ($error = $this->validateInput($rules)) {
            return $error;
        }

        $member =  \Auth::guard('member')->user();
        // $goods = "[{"goods_id":1,"sku_id":1,"num":1},{"goods_id":1,"sku_id":2,"num":1}]";
        $this->validated['member'] = $member;

        $this->validated['goods'] = json_decode($this->validated['goods'], 1);

        $msg = '';
        $result = Order::getPrice($this->validated, $msg);

        if (!$result)
        {
            return $this->output(200500, '', $msg);
        }

        return $this->output(200, $result);

    }

    /**
     * @api {post} /order/cancel
     * 取消订单
     */
    public function cancel(Request $request)
    {
        $rules = [
            'order_bn'     => 'required|string',
        ];

        if ($error = $this->validateInput($rules)) {
            return $error;
        }

        $member =  \Auth::guard('member')->user();
        $this->validated['member'] = $member;

        $msg = '';
        $result = Order::cancel($this->validated, $msg);

        if (!$result)
        {
            return $this->output(200500, '', $msg);
        }

        return $this->output(200, $result);
    }

    /**
     * @api {post} /order/toPay
     * 去支付
     */
    public function toPay(Request $request)
    {
        $rules = [
            'order_bn'     => 'required|string',
            'payment_code'      => 'required|string',
        ];

        if ($error = $this->validateInput($rules)) {
            return $error;
        }

        $member =  \Auth::guard('member')->user();
        // $this->validated['member'] = $member;

        // $msg = '';
        // $result = Order::toPayed($this->validated, $msg);

        // 获取订单信息
        $order = Order::where('order_bn', $this->validated['order_bn'])->where('member_id', $member->member_id)->with('detail', 'member', 'address')->first();

        if (!$order)
        {
            return $this->output(200500, '', '订单不存在');
        }

        if (!$order->pay_status == 'paid')
        {
            return $this->output(200500, '', '订单已支付，请勿重复支付');
        }

        if (!$order->pay_status == 'paid')
        {
            return $this->output(200500, '', '订单已退款，请勿支付');
        }

        $order = $order->toArray();
        // dd($order);
        $goods_name = array_column($order['detail'], 'goods_name');
        $goods_num = array_column($order['detail'], 'num');

        $payment_code = $this->validated['payment_code'];

        switch ($payment_code) {
            case 'lianlianpay':
                // 连连付
                $lian = new Lianlianpay();
                // $result = $lian->toPay($order);
                // dd($result);
                $res = $lian->createTrade($order);
                // $res_ = $lian->toPay($res);
                // dd($res);

                if ($res['ret_code']=='0000')
                {
                    $result = $lian->toPay($order, $res);
                    // dd($res, $result);
                    if ($result['ret_code'] != '0000')
                    {
                        return $this->output(200500, '', '网关支付失败:'.$result['ret_msg']);
                    }

                }
                else
                {
                    return $this->output(200500, '', '创建预支付失败:'.$res['ret_msg']);
                }

                break;
            case 'lianlpay_offline':
                $lian = new Lianlianpay();
                // $result = $lian->toPay($order);
                // dd($result);
                $result = $lian->offlineCreateTrade($order);
                // $res_ = $lian->toPay($res);
                // dd($res);
                Log::info('lianlpay_offline_result:'. json_encode($result));
                if ($result['ret_code']=='0000')
                {
                    // $result = $lian->getPayLink($order, $res);
                    // dd($res, $result);
                    // if ($result['ret_code'] != '0000')
                    // {
                    //     return $this->output(200500, '', '网关支付失败:'.$result['ret_msg']);
                    // }

                }
                elseif($result['ret_code']=='1010')
                {
                    $payment = Payment::where('order_bn',  $order['order_bn'])->where('payment_code', $payment_code)->where('status', 'ready')->first();
                    $pay_result = json_decode($payment->pay_result, 1);
                    $result = $lian->getPayLink($order, $pay_result);
                    Log::info('lianlpay_offline_result1:'. json_encode($result));
                }
                else
                {
                    return $this->output(200500, '', '创建预支付失败:'.$result['ret_msg']);
                }

                break;
            case 'sumpay':
                // 统统付
                $payData = [
                    // 公共参数
                    'version' => '1.0',
                    'format' => 'JSON',
                    'app_id' => env('SUMPAY_APPID'),
                    'timestamp' => date('YmdHis'),
                    'terminal_type' => 'api',
                    // 'sign_type' => 'CERT',
                    // 'sign' => '',
                    'service' => 'fosun.sumpay.api.trade.mini.program.order.apply',
                ];

                // 业务参数
                $payData['mer_no'] = env('SUMPAY_APPID');
                $payData['trade_code'] = 'T0001';
                $payData['user_id'] = $member->member_id;
                $payData['order_no'] = $order['order_bn'];
                $payData['order_time'] = date('YmdHis', strtotime($order['created_at']));
                $payData['order_amount'] = $order['amount'];
                $payData['business_code'] = '25';
                $payData['need_notify'] = '1';
                $payData['notify_url'] = env('SUMPAY_NOTIFY_URL');
                $payData['currency'] = 'CNY';
                $payData['goods_name'] = implode(',', $goods_name); //
                $payData['goods_num'] = array_sum($goods_num); //
                $payData['goods_type'] = '1';

                $payData['identity'] = json_encode(['name'=>'张三', 'number'=>'165876185912120523']);

                // dd($payData);
                // 需要AES加密的字段
                $encrypted_fields = array (
                    "identity",
                );
                // 需转化UTF-8的字段
                $charset_change_fields = array (
                    "notify_url",
                    'goods_name'
                );
                // 需要base64的字段
                $special_fields = array (
                    "terminal_info",
                    "notify_url",
                    'goods_name'
                );
                $json_array_fields = array();
                $defaultCharset = 'UTF-8';

                $domain = URL::previous();

                $url = env('SUMPAY_URL');
                // $fpx_file = "/Users/fuxiudong/data/httpd/work_php81/enzhongfu/manager/app/Services/Payment/Sumpay/cer/yixuntiankong.pfx";
                $fpx_file = env('SUMPAY_FPX_FILE');
                // $pem_file = "/Users/fuxiudong/data/httpd/work_php81/enzhongfu/manager/app/Services/Payment/Sumpay/cer/dev_pub.pem";
                $pem_file = env('SUMPAY_PEM_FILE');

                $res = Sumpay::execute($url, 'UTF-8', $payData, $fpx_file, "sumpay", $pem_file, $domain, $charset_change_fields, $encrypted_fields, $special_fields, $json_array_fields, $defaultCharset);

                dd('ss',$res);
                break;
            default:
                // code...
                break;
        }

        if ($result['ret_code']=='0000')
        {
            $new_payment = Payment::where('order_bn', $order['order_bn'])->where('pay_no', $result['accp_txno'])->first();
            if (!$new_payment)
            {
                // 创建支付单
                $payment_data = [
                    'order_bn' => $order['order_bn'],
                    'pay_no' => $result['accp_txno'],
                    'member_id' => $order['member_id'],
                    'type' => 'payed',
                    'status' => 'ready',
                    'paid_amount' => $order['amount'],
                    'discount_amount' => $order['discount_amount'],
                    'payment_code' => $payment_code,
                    'pre_result' => '',
                    'pay_result' => json_encode($result),
                ];

               Payment::create($payment_data);
            }
        }

        return $this->output(200, $result);
    }

    /**
     * @api {post} /order/checkOrderPay
     * 检测订单是否支付
     */
    public function checkOrderPay(Request $request)
    {
        $rules = [
            'pay_no'     => 'required|string',
        ];

        if ($error = $this->validateInput($rules)) {
            return $error;
        }

        $member =  \Auth::guard('member')->user();
        $this->validated['member'] = $member;

        $result = Payment::where('order_bn' ,$this->validated['pay_no'])->where('status', 'success')->first();

        if (!$result)
        {
            return $this->output(200500, '', '订单尚未支付成功');
        }
        else
        {
            $status = $result->status;
        }

        return $this->output(200, ['status' => $status]);
    }

}
